//
//  WPCoinTopUp.m
//  wobingwoyi
//
//  Created by WGP on 16/8/4.
//  Copyright © 2016年 WGP. All rights reserved.
//

#import "WPCoinTopUp.h"
#import "WPCoinTopUpCVC.h"
#import <StoreKit/StoreKit.h>

#define SANDBOX_URL @"https://sandbox.itunes.apple.com/verifyReceipt"
#define BUY_URL @"https://buy.itunes.apple.com/verifyReceipt"

@interface WPCoinTopUp ()<UICollectionViewDelegate,UICollectionViewDataSource,SKProductsRequestDelegate,SKPaymentTransactionObserver,UIAlertViewDelegate>

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *collectionViewHeightConstraint;
@property (weak, nonatomic) IBOutlet UICollectionViewFlowLayout *layout;
@property (nonatomic, strong) NSMutableArray *products;
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property(nonatomic,strong)WPBtnNoHighLight *currentBtn;
@property(nonatomic,strong)WPCoinTopUpCVC *currentCell;

@property(nonatomic,strong)UIAlertView *failedAlertView;

@end

@implementation WPCoinTopUp

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if (self.hideNavBar)
    {
        self.navigationController.navigationBar.hidden = YES;
    }
    
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
    
    [self.collectionView registerClass:[WPCoinTopUpCVC class] forCellWithReuseIdentifier:@"WPCoinTopUpCVC"];
    
    CGFloat itemW = (SCREEN_WIDTH-4*15)/3;
    CGFloat itemH = 60;
    CGSize itemSize = CGSizeMake(itemW, itemH);
    self.layout.itemSize = itemSize;
    self.collectionViewHeightConstraint.constant = 2*itemH+15;
    
    self.layout.minimumLineSpacing = 15;
    self.layout.minimumInteritemSpacing = 15;
    
//    请求商品信息
    [self requestProductInformation];
}

#pragma mark - collectionView的代理方法
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.products.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    WPCoinTopUpCVC *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"WPCoinTopUpCVC" forIndexPath:indexPath];
    
    __weak typeof(cell) weakCell = cell;
    cell.bgBtnDidClick = ^(WPBtnNoHighLight *btn)
    {
        if(self.currentBtn == btn)
        {
            return ;
        }

        self.currentBtn.selected = NO;
        
        self.currentCell.priceLabel.textColor = GLobalFontColor;
        self.currentCell.descriptionLabel.textColor = GloballightFontColor;
        
        self.currentCell = weakCell;
        self.currentBtn = btn;
        self.currentBtn.selected = YES;
        
        weakCell.priceLabel.textColor = [UIColor whiteColor];
        weakCell.descriptionLabel.textColor = [UIColor whiteColor];
    };
    cell.product = self.products[indexPath.item];
    return cell;
}

-(void)requestProductInformation
{
    //  1. 请求可售商品
    SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers:[NSSet setWithObjects:@"com.wobingwoyi.wbwy5.3",@"com.wobingwoyi.wbwy5.6",@"com.wobingwoyi.wbwy5.12",@"com.wobingwoyi.wbwy5.18",@"com.wobingwoyi.wbwy5.30",@"com.wobingwoyi.wbwy5.60", nil]];
    
    // 2.设置代理
    request.delegate = self;
    
    // 3. 发送请求
    [request start];
    
    //    4.提示框
    [SVProgressHUD showWithStatus:@"正在请求商品信息"];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
}

// Sent immediately before -requestDidFinish:/// 当苹果返回可售商品时调用
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response
{
    self.products = [NSMutableArray arrayWithArray:response.products];
    
    if (!self.products.count)
    {
        [self dismiss];
//        没有获取到产品信息
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示信息" message:@"获取产品信息失败" delegate:self cancelButtonTitle:@"关闭" otherButtonTitles:@"重试", nil];
        self.failedAlertView = alertView;
        [alertView show];
        
        return ;
    }
//    排序
    SKProduct *temp = nil;
    for(int i=0; i<self.products.count-1; i++)
        for(int j=0; j<self.products.count-1-i;j++)
        {
            if([[self.products[j] price] intValue] > [[self.products[j+1] price] intValue])
            {
                temp = self.products[j];
                self.products[j] = self.products[j+1];
                self.products[j+1] = temp;
            }
        }
    //  刷新表格
    [self.collectionView reloadData];
    
    [SVProgressHUD dismiss];
    
}

- (void)request:(SKRequest *)request didFailWithError:(NSError *)error
{

    [SVProgressHUD dismiss];
    UIAlertView *alerView =  [[UIAlertView alloc] initWithTitle:@"提示信息" message:[error localizedDescription] delegate:self cancelButtonTitle:@"重试" otherButtonTitles:@"取消",nil];
    [alerView show];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
}

- (IBAction)buynowBtnDidClick
{
    if (!self.currentCell)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示信息" message:@"请选择充值医票" delegate:nil cancelButtonTitle:@"知道了" otherButtonTitles:nil];
        [alert show];
    }
    else
    {
       [SVProgressHUD showWithStatus:@"正在发送购买请求"];
        
        NSIndexPath *indexPath = [self.collectionView indexPathForCell:self.currentCell];
        //  1. 取出商品
        SKProduct *product = self.products[indexPath.row];
        //  2. 创建一个支付票据
        SKPayment *payment = [SKPayment paymentWithProduct:product];
        
        //  添加一个监听（类似代理）
        [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
        //  3. 把票据对象添加到支付队列
        [[SKPaymentQueue defaultQueue] addPayment:payment];
    }

}

/// 当交易状态发生改变了调用
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray<SKPaymentTransaction *> *)transactions{
    
    
    //    SKPaymentTransactionStatePurchasing,     正在交易
    //    SKPaymentTransactionStatePurchased,      交易完成后，客户端完成交易
    //    SKPaymentTransactionStateFailed,         交易失败
    //    SKPaymentTransactionStateRestored,       恢复交易，客户端完成交易
    //    SKPaymentTransactionStateDeferred NS_ENUM_AVAILABLE_IOS(8_0),  交易已经被添加到交易队列，但是交易状态不明确
    
    for (SKPaymentTransaction *transaction  in transactions) {
        
        switch (transaction.transactionState) {
            case SKPaymentTransactionStatePurchasing:
                WPLog(@"正在交易");
                [SVProgressHUD showWithStatus:@"正在请求付费信息"];
                break;
            case SKPaymentTransactionStatePurchased:
                WPLog(@"交易完成");
                [SVProgressHUD dismiss];
                //              服务器二次验证
                [self completeTransaction:transaction];
                break;
            case SKPaymentTransactionStateFailed:
                WPLog(@"交易失败");
                [SVProgressHUD dismiss];
                [self failedTransaction:transaction];
                break;
            case SKPaymentTransactionStateRestored:
                WPLog(@"恢复交易,客户端完成交易");
                [queue finishTransaction:transaction];
                break;
            default:
                [SVProgressHUD dismiss];
                break;
        }
    }
    
}


- (void)completeTransaction:(SKPaymentTransaction *)transaction {
    
    WPLog(@"-------------------支付完成--------------------");
    [self commitSeversSucceeWithTransaction:transaction];
}

- (void)commitSeversSucceeWithTransaction:(SKPaymentTransaction *)transaction

{
    // 验证凭据，获取到苹果返回的交易凭据
    // appStoreReceiptURL iOS7.0增加的，购买交易完成后，会将凭据存放在该地址
    NSURL *receiptURL = [[NSBundle mainBundle] appStoreReceiptURL];
    // 从沙盒中获取到购买凭据
    NSData *receiptData = [NSData dataWithContentsOfURL:receiptURL];
    
//    // 发送网络POST请求，对购买凭据进行验证
//    NSURL *url = [NSURL URLWithString:SANDBOX_URL];
//    // 国内访问苹果服务器比较慢，timeoutInterval需要长一点
//    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0f];
//    request.HTTPMethod = @"POST";
    
    // 在网络中传输数据，大多情况下是传输的字符串而不是二进制数据
    // 传输的是BASE64编码的字符串
    /**
     BASE64 常用的编码方案，通常用于数据传输，以及加密算法的基础算法，传输过程中能够保证数据传输的稳定性
     BASE64是可以编码和解码的
     */
    NSString *encodeStr = [receiptData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
    NSString *payload = [NSString stringWithFormat:@"{\"receipt-data\" : \"%@\"}", encodeStr];
//    NSData *payloadData = [payload dataUsingEncoding:NSUTF8StringEncoding];
//    request.HTTPBody = payloadData;
//    // 提交验证请求，并获得官方的验证JSON结果
//    NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    
  
    NSString *url = @"apple/testorder.do";
    NSDictionary *dict = @{@"order":payload};
    
    [[WPNetWorkManager sharedNetWorkManager] POST:url parameters:dict progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *dict = (NSDictionary *)responseObject;
        if ([dict[@"result"] isEqualToString:@"success"])
        {
            
        }
        else
        {
            UIAlertView *alerView =  [[UIAlertView alloc] initWithTitle:@"友情提示" message:@"服务器验证失败，请重新尝试购买。如果充值遇到问题，请联系我病我医客服" delegate:nil cancelButtonTitle:@"关闭" otherButtonTitles:nil];
            [alerView show];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        WPLog(@"%@",error);
    }];
    
    [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
}

- (void)failedTransaction:(SKPaymentTransaction *)transaction
{
//    if(transaction.error.code == 0)
//         {
//            UIAlertView *alerView2 =  [[UIAlertView alloc] initWithTitle:@"友情提示" message:@"购买失败，请重新尝试购买" delegate:nil cancelButtonTitle:@"关闭" otherButtonTitles:nil];
//    
//                 [alerView2 show];
//            }
//         else if(transaction.error.code == 2)
//         {
//          UIAlertView *alerView2 =  [[UIAlertView alloc] initWithTitle:@"友情提示" message:@"您已取消该购买"                                                                   delegate:nil cancelButtonTitle:@"关闭" otherButtonTitles:nil];
//            
//               [alerView2 show];
//          }
    WPLog(@"%@",transaction.error);
    
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView == self.failedAlertView)
    {
        if (buttonIndex == 1)
        {
            [self requestProductInformation];
        }
    }
    else
    {
        if (buttonIndex == 0)
        {
            [self requestProductInformation];
        }
    }
}

- (IBAction)back
{
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    
    if (self.isDismiss)
    {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
    else
    {
        [self.navigationController popViewControllerAnimated:YES];
    }
    
//    在阅读排名购买金币后重新请求病例比较一下
    if (self.backBlock)
    {
        self.backBlock();
    }
}

-(void)dealloc
{
    WPLog(@"死了");
    [[SKPaymentQueue defaultQueue] removeTransactionObserver:self];//解除监听
}

@end
















